#pragma once
#include "Socket.hpp"
using handler_t = std::function<void(Socket* newsockp)>;
class TcpServer
{
public:
    TcpServer(int port):_sockfd(std::make_unique<TcpSocket>(port))
    {
    }
    void Init(handler_t handler)
    {
        _handler = handler;
        _sockfd->BuildTcpSocket();
    }
    void Start()
    {
        while(true)
        {
            //1.accept
            InetAddr client;
            auto newsockp = _sockfd->Accept(&client);
            //LOG(LogLevel::INFO)<<"accpet success,new sockfd: "<<client.Ip()<<":"<<client.Port();
            //2.IO 这里将IO交给上一层
            pid_t pid = fork();
            if(pid==0)
            {
                _sockfd->Close();
                if(fork()>0)
                {
                    exit(0);
                }
                //孙子进程
                //std::string req;
                //newsockp->Recv(&req);
                _handler(newsockp);
                //newsockfd->Send(resp);
            }
            newsockp->Close();

            // //cookie过期的解决方案
            // _handler(newsockp);

        }
    }
    ~TcpServer()
    {
    }

private:
    std::unique_ptr<Socket> _sockfd;
    handler_t _handler;
};